let TB_ROUND = {
    1: {
        monsterNum: 40,
        monsterValume: 20,
        monsterMap: {
            301: 1,
        }
    },
    2: {
        monsterNum: 50,
        monsterValume: 30,
        monsterMap: {
            301: 5,
            302: 1,
        }
    },
    3: {
        monsterNum: 60,
        monsterValume: 40,
        monsterMap: {
            301: 10,
            302: 2,
            303: 1,
        }
    },
}
let TB_MONSTER = {
    301: {
        speed: 7,
        hp: 100,
        attack: 10,
    },
    302: {
        speed: 3,
        hp: 1000,
        attack: 20
    },
    303: {
        speed: 8,
        hp: 500,
        attack: 30
    }
}
let MONSTER_LIST = [301, 302, 303];
class monsterManager {
    constructor() {
        this._time = 0;
        this.fps = 1;
        this.monsterLayer = null;
        this.monsterPosList = [];
        this.tempPosList = [];
        this.uid = 1000;
        this.Cid = 10;
        this.length = 80;
        this.speed = 5;
        this.monsterList = {
            //id:monster
        };
        this.monsterPool = [];//当前回合的怪物池
        this.maxMonsterValume = 0;//当前回合数的最大容量
        this.monsterNum = 0;//已创建怪物数总量
        this.monsterNumMax = 0;//本回合怪物数总量
        this.monsterData = {};//专门存放怪物的，不包括小怪物（小怪物包含在母亲里面）
        this.momData = {};//专门存放母亲的数据
        this.rewardData = {};//生成的奖励
        this.rewardID = 1000;//奖励id初始化
        //不能这样子写，window会先加载，而window调用了这个类的构造函数
        // this.TB_monster = g_Res.getRes("table", "TB_MONSTER").json;
        cc.log(g_Res.getRes("table", "TB_MONSTER"));
        this.dieLayer = null;
    }
    setLayer(layer) {
        this.monsterLayer = layer;
    }
    setDieLayer(layer) {
        this.dieLayer = layer;
    }
    setMonsterPosNode(node) {
        let childList = node.children;
        for (let child of childList) {
            this.monsterPosList.push({
                x: child.x,
                y: child.y,
            })
        }
    }
    getMonsterByUid(uid) {
        return this.monsterList[uid];
    }
    getAllMonster() {
        return this.monsterList;
    }
    getAllMom() {
        return this.momData;
    }
    getMonsterNum() {
        return {
            monsternum: this.monsterNum,
            monsternummax: this.monsterNumMax
        };
    }
    //生成奖励
    generateReward(monsterID) {
        let res = g_Res.getRes("prefab", "icon_diamond");
        let reward = cc.instantiate(res);
        this.rewardData[this.rewardID++] = reward;
        game.rewardLayer.addChild(reward);
        let tMonster = this.getMonsterByUid(monsterID);
        reward.setPosition(tMonster.x, tMonster.y);
    }
    playAnimForDie(monster) {
        let effic = cc.instantiate(g_Res.getRes("prefab", "bron"));
        this.dieLayer.addChild(effic);
        effic.setPosition(monster.x, monster.y);
        let anime = effic.getComponent(cc.Animation);
        anime.on(cc.Animation.EventType.FINISHED, () => { effic.destroy() });
    }
    launchMonster() {
        //建了一个资源表，通过资源管理器进行调用
        let TB_round = g_Res.getRes("table", "TB_ROUND").json;
        let info = TB_round[game.getRound()];

        if (!info) {
            return;
        }
        //      发射怪物
        let sum = 0;
        //获取怪物权重
        let lstShape = [];
        for (let shape in info.monsterMap) {
            lstShape.push(shape);
            sum += info.monsterMap[shape];
        }
        this.monsterNumMax = info.monsterNum;
        //从小到大
        lstShape.sort((a, b) => { return info.monsterMap[a] - info.monsterMap[b] });
        //创造一个怪物池，并打乱
        let monsterPool = [];
        // {
        //     monsterNum: 40,
        //     monsterValume: 20,
        //     monsterMap: {
        //         301: 1,
        //     }
        for (let shape of lstShape) {
            let weight = info.monsterMap[shape];
            let tNum = Math.floor(info.monsterNum * weight / sum);

            while (tNum--) {
                monsterPool.push(shape);
            }
        }
        while (monsterPool.length < info.monsterNum) {
            monsterPool.push(lstShape[lstShape.length - 1]);
        }
        //打乱
        monsterPool.sort(() => { return Math.random() - 0.5 });
        this.monsterPool = monsterPool;
        this.monsterValume = info.monsterValume;
        this.monsterNum = 0;
        this.monsterMax = info.monsterNum;
    }
    crtSpecificMonster(shape, pos, mom) {
        //用于能够召唤小怪的ai
        if (!this.monsterLayer || this.monsterPosList.length == 0) {
            return;
        }
        let name = "enemy" + shape;
        let pre = g_Res.getRes("actor", name);
        let tMonster = cc.instantiate(pre);
        this.monsterLayer.addChild(tMonster);
        let TB_monster = g_Res.getRes("table", "TB_MONSTER").json;
        let { speed, hp, attack, ai } = TB_monster[shape];
        tMonster.x = pos.x;
        tMonster.y = pos.y;
        tMonster.speed = speed;
        tMonster.launchTime = 0;//发射时间要部署在节点上面，部署在ai上面会和其他的monster公用
        tMonster.createTime = 0;//小怪生成时间与上面同理
        tMonster.HP = hp;
        tMonster.ID = mom.Cid++;//是根据母亲cid的赋值
        tMonster.attack = attack;
        tMonster.debuff = 0;
        tMonster.mom = mom;//将母亲保存，且只有孩子怪物有这个内容
        for (let i of ai) {
            g_CAIManager.register(tMonster, i);
        }
        mom.childNum++;
        mom.data[tMonster.ID] = tMonster;//将孩子管理起来
    }
    createMonster() {
        if (!this.monsterLayer || this.monsterPosList.length == 0) {
            return;
        }
        if (this.monsterPool.length == 0) {
            return;
        }
        let curMonsterNum = Object.keys(this.monsterData).length;
        if (curMonsterNum >= this.monsterValume) {
            return;
        }

        this.monsterNum++;

        let shape = this.monsterPool.pop();
        //let idx = Math.floor(Math.random() * MONSTER_LIST.length);
        let monsterName = "enemy" + shape;
        let pre = g_Res.getRes("actor", monsterName);

        let tMonster = cc.instantiate(pre);
        this.monsterLayer.addChild(tMonster);
        if (this.tempPosList.length == 0) {
            this.tempPosList = JSON.parse(JSON.stringify(this.monsterPosList));
            //打乱排序
            this.tempPosList.sort(() => {
                return Math.random() - 0.5;
            });
        }
        let pos = this.tempPosList.pop();
        //通过资源管理器获取一个表
        let TB_monster = g_Res.getRes("table", "TB_MONSTER").json;
        let { speed, hp, attack, ai } = TB_monster[shape];
        tMonster.x = pos.x;
        tMonster.y = pos.y;
        tMonster.speed = speed;
        tMonster.launchTime = 0;//发射时间要部署在节点上面，部署在ai上面会和其他的monster公用
        tMonster.createTime = 0;//小怪生成时间与上面同理
        tMonster.data = {};//管理生成的小怪呢
        tMonster.HP = hp;
        tMonster.MaxHP = hp;
        tMonster.ID = this.uid++;
        //孩子怪兽的id起始
        tMonster.attack = attack;
        tMonster.debuff = 0;
        //给怪物搭载ai
        for (let i of ai) {
            g_CAIManager.register(tMonster, i);
            //需要给1003的ai额外处理
            if (i == 1003) {
                tMonster.Cid = this.Cid;//母亲怪物独有的
                tMonster.childNum = 0;
                this.Cid += 10;
                this.momData[tMonster.ID] = tMonster;
            }
            if (i == 1004) {
                tMonster.maxShieldsTime = 20//最大护盾时间
                tMonster.shieldsTime = 20//护盾时间
                tMonster.shields = 0;//护盾值
                tMonster.interval = 10;//持续时间
            }
        }

        this.monsterList[tMonster.ID] = tMonster;
        this.debuff = 0;
    }
    onHurt(monster, hurt, type = 1) {
        if (!monster) {
            return;
        }
        cc.log(monster, "monster");
        //type：1、2、3、4、5普通伤害、毒、玩家受伤、灼烧伤害、暴击伤害
        //还需要考虑对护盾的伤害;
        if (monster.shields > 0) {
            //先扣护盾再扣血
            let myHurt = hurt;
            myHurt -= monster.shields;
            monster.shields -= hurt;
            cc.log("shields", monster.shields);
            if (monster.shields <= 0) {
                //护盾在此刻被打碎了
                //需要删除护盾
                cc.log("aaaaaaaaaaa");
                monster.insShields.destroy();
            }
            if (myHurt >= 0) {
                hurt = myHurt;
            } else {
                hurt = 0;
            }
        }
        monster.HP -= hurt;
        game.role.script.doLeech(hurt);
        g_Hurt.showHurtLabel(monster, hurt, type);
        let monsterID = monster.ID;
        cc.log("hp", monster.HP);
        if (monster.HP <= 0) {
            //怪物血量为0,消灭怪物
            game.addKill();
            this.playAnimForDie(monster);
            this.generateReward(monster.ID);//生成奖励
            if (monster.Cid) {
                //母体
                //先杀死孩子
                for (let id in monster.data) {
                    cMonster = monster.data[id];
                    g_CAIManager.delAI(cMonster);
                    cMonster.destroy();
                }
                //需要先删除母体里面的孩子怪物数据
                monster.data = {};
            }
            delete this.monsterList[monster.ID];
            g_CAIManager.delAI(monster);
            monster.destroy();
        }
    }
    //子弹碰撞到孩子时调用
    AI1003COnHurt(monster, hurt, type) {
        if (!monster) {
            return;
        }
        if (monster.shields > 0) {
            //先扣护盾再扣血
            let myHurt = hurt;
            myHurt -= monster.shields;
            monster.shields -= hurt;
            cc.log("shields", monster.shields);
            if (monster.shields <= 0) {
                //护盾在此刻被打碎了
                //需要删除护盾
                cc.log("aaaaaaaaaaa");
                monster.insShields.destroy();
            }
            if (myHurt >= 0) {
                hurt = myHurt;
            } else {
                hurt = 0;
            }
        }
        monster.HP -= hurt;
        monster.HP -= hurt;
        game.role.script.doLeech(hurt);
        g_Hurt.showHurtLabel(monster, hurt, type);
        let monsterID = monster.ID;
        if (monster.HP <= 0) {
            //怪物血量为0,消灭怪物
            let mom = monster.mom;//获取母亲
            this.playAnimForDie(monster);
            delete mom.data[monster.ID];
            //扣母亲的血
            this.onHurt(mom, mom.MaxHP * 0.1);
            g_CAIManager.delAI(monster);
            monster.destroy();
        }
    }
    clear() {
        this.monsterLayer = null;
        this.monsterPosList = [];
        this.tempPosList = [];
        this.uid = 1000;
        this.monsterList = {};
        this.monsterPool = [];
        this.monsterData = {};
        this.rewardData = {};
        this.rewardID = 1000;
        this.dieLayer = null;
    }
    update(dt) {
        this._time += dt;
        if (this._time > this.fps) {
            this._time -= this.fps;
            this.createMonster();
        }
        // this.pickReward();
    }
}
window.g_Monster = new monsterManager;
